package common.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP工具类
 *
 * @author 米泽鹏
 */
@Slf4j
public class IpUtils {

	private static final String UNKNOWN = "unknown";
	private static final String COMMA_EN = ",";
	private static final String IP_LOCAL_HOST_IPV4 = "127.0.0.1";
	private static final String IP_LOCAL_HOST_IPV6 = "0:0:0:0:0:0:0:1";

	/**
	 * 获取ip地址
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 添加对X-Real-IP头部的检查
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.contains(COMMA_EN)) {
			ip = ip.substring(ip.lastIndexOf(COMMA_EN) + 1).trim();
		}
		if (IP_LOCAL_HOST_IPV4.equals(ip) || IP_LOCAL_HOST_IPV6.equals(ip)) {
			// 根据网卡取本机配置的IP
			InetAddress inet;
			try {
				inet = InetAddress.getLocalHost();
				ip = inet.getHostAddress();
			} catch (UnknownHostException e) {
				log.error("获取IP地址发生异常", e);
			}
		}
		log.info("获取IP地址:{}", ip);
		return ip;
	}

}
